"""
任务列表页面

显示和管理所有任务的页面
"""

import tkinter as tk
from tkinter import ttk, messagebox
from pathlib import Path
import sys
from datetime import datetime, timedelta

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame, 
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class TaskListPage(BasePage):
    """任务列表页面"""
    
    def __init__(self, parent, app):
        super().__init__(parent, app)
        self.tasks = []  # 任务数据
        self.filtered_tasks = []  # 过滤后的任务
        
    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)
        
        # 页面标题
        self.create_header()
        
        # 工具栏
        self.create_toolbar()
        
        # 任务列表
        self.create_task_list()
        
        # 加载示例数据
        self.load_sample_data()
    
    def create_header(self):
        """创建页面标题"""
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 标题区域
        title_container = ttk.Frame(header_frame)
        title_container.pack(side="left", fill="x", expand=True)
        
        title_label = ttk.Label(
            title_container,
            text="📋 任务列表",
            style='Title.TLabel'
        )
        title_label.pack(side="left")
        
        # 副标题
        subtitle_label = ttk.Label(
            title_container,
            text="查看和管理所有混剪任务",
            style='Muted.TLabel'
        )
        subtitle_label.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))
        
        # 操作按钮区域
        action_frame = ttk.Frame(header_frame)
        action_frame.pack(side="right")
        
        # 刷新按钮
        refresh_btn = create_secondary_button(
            action_frame,
            text="🔄 刷新",
            command=self.refresh_tasks
        )
        refresh_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))
    
    def create_toolbar(self):
        """创建工具栏"""
        toolbar_frame = create_card_frame(self.frame, "筛选和操作")
        toolbar_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 第一行：筛选控件
        filter_row = ttk.Frame(toolbar_frame)
        filter_row.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        # 状态筛选
        status_container = ttk.Frame(filter_row)
        status_container.pack(side="left")
        
        ttk.Label(status_container, text="状态筛选:", style='Heading.TLabel').pack(side="left")
        
        self.status_filter_var = tk.StringVar(value="all")
        status_combo = ttk.Combobox(
            status_container,
            textvariable=self.status_filter_var,
            values=["all", "⏳ 等待中", "🔄 进行中", "✅ 已完成", "❌ 失败", "⏸️ 暂停"],
            state="readonly",
            width=12
        )
        status_combo.pack(side="left", padx=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['lg']))
        status_combo.bind("<<ComboboxSelected>>", self.on_filter_changed)
        
        # 类型筛选
        type_container = ttk.Frame(filter_row)
        type_container.pack(side="left")
        
        ttk.Label(type_container, text="类型筛选:", style='Heading.TLabel').pack(side="left")
        
        self.type_filter_var = tk.StringVar(value="all")
        type_combo = ttk.Combobox(
            type_container,
            textvariable=self.type_filter_var,
            values=["all", "🎬 视频混剪", "🖼️ 图片处理", "🎵 音频处理", "📊 数据分析"],
            state="readonly",
            width=12
        )
        type_combo.pack(side="left", padx=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['lg']))
        type_combo.bind("<<ComboboxSelected>>", self.on_filter_changed)
        
        # 搜索框
        search_container = ttk.Frame(filter_row)
        search_container.pack(side="right")
        
        ttk.Label(search_container, text="搜索:", style='Heading.TLabel').pack(side="left")
        self.search_var = tk.StringVar()
        search_entry = ttk.Entry(search_container, textvariable=self.search_var, width=25)
        search_entry.pack(side="left", padx=(DesignSystem.SPACING['sm'], 0))
        search_entry.bind("<KeyRelease>", self.on_search_changed)
        
        # 第二行：操作按钮
        action_row = ttk.Frame(toolbar_frame)
        action_row.pack(fill="x")
        
        # 左侧按钮组
        left_actions = ttk.Frame(action_row)
        left_actions.pack(side="left")
        
        new_task_btn = create_primary_button(
            left_actions,
            text="🎬 新建任务",
            command=self.create_new_task
        )
        new_task_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))
        
        batch_btn = create_secondary_button(
            left_actions,
            text="📦 批量操作",
            command=self.batch_operations
        )
        batch_btn.pack(side="left")
        
        # 右侧按钮组
        right_actions = ttk.Frame(action_row)
        right_actions.pack(side="right")
        
        export_btn = create_secondary_button(
            right_actions,
            text="📤 导出报告",
            command=self.export_report
        )
        export_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))
        
        clear_btn = create_danger_button(
            right_actions,
            text="🗑️ 清理完成",
            command=self.clear_completed
        )
        clear_btn.pack(side="right")
    
    def create_task_list(self):
        """创建任务列表"""
        list_frame = create_card_frame(self.frame, "任务列表")
        list_frame.pack(fill="both", expand=True)
        
        # 列表容器
        list_container = ttk.Frame(list_frame)
        list_container.pack(fill="both", expand=True)
        
        # 创建Treeview
        columns = ('task_id', 'name', 'type', 'product', 'progress', 'status', 'created', 'duration')
        self.task_tree = ttk.Treeview(list_container, columns=columns, show='headings', height=15)
        
        # 设置列标题和宽度
        column_config = {
            'task_id': ('🆔 任务ID', 100),
            'name': ('📝 任务名称', 200),
            'type': ('🏷️ 类型', 100),
            'product': ('📦 关联商品', 150),
            'progress': ('📊 进度', 80),
            'status': ('🔄 状态', 100),
            'created': ('📅 创建时间', 150),
            'duration': ('⏱️ 耗时', 80)
        }
        
        for col, (title, width) in column_config.items():
            self.task_tree.heading(col, text=title)
            self.task_tree.column(col, width=width, anchor='center' if col not in ['name', 'product'] else 'w')
        
        # 滚动条
        v_scrollbar = ttk.Scrollbar(list_container, orient="vertical", command=self.task_tree.yview)
        h_scrollbar = ttk.Scrollbar(list_container, orient="horizontal", command=self.task_tree.xview)
        self.task_tree.configure(yscrollcommand=v_scrollbar.set, xscrollcommand=h_scrollbar.set)
        
        # 布局
        self.task_tree.grid(row=0, column=0, sticky="nsew")
        v_scrollbar.grid(row=0, column=1, sticky="ns")
        h_scrollbar.grid(row=1, column=0, sticky="ew")
        
        list_container.grid_rowconfigure(0, weight=1)
        list_container.grid_columnconfigure(0, weight=1)
        
        # 绑定事件
        self.task_tree.bind("<Double-1>", self.on_item_double_click)
        self.task_tree.bind("<Button-3>", self.show_context_menu)
        
        # 添加空状态提示
        self.create_empty_state(list_frame)
    
    def create_empty_state(self, parent):
        """创建空状态提示"""
        self.empty_frame = ttk.Frame(parent)
        
        empty_icon = ttk.Label(
            self.empty_frame,
            text="📋",
            font=(DesignSystem.FONTS['family_primary'], 48)
        )
        empty_icon.pack(pady=(50, DesignSystem.SPACING['lg']))
        
        empty_title = ttk.Label(
            self.empty_frame,
            text="暂无任务",
            style='Heading.TLabel'
        )
        empty_title.pack()
        
        empty_desc = ttk.Label(
            self.empty_frame,
            text="点击「新建任务」按钮创建您的第一个混剪任务",
            style='Muted.TLabel'
        )
        empty_desc.pack(pady=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['xl']))
        
        create_first_btn = create_primary_button(
            self.empty_frame,
            text="🎬 创建第一个任务",
            command=self.create_new_task
        )
        create_first_btn.pack()
    
    def load_sample_data(self):
        """加载示例数据"""
        now = datetime.now()
        sample_tasks = [
            {
                'task_id': 'T001',
                'name': '时尚T恤宣传视频',
                'type': '🎬 视频混剪',
                'product': '时尚休闲T恤',
                'progress': 100,
                'status': '✅ 已完成',
                'created': (now - timedelta(hours=2)).strftime('%Y-%m-%d %H:%M'),
                'duration': '15分钟'
            },
            {
                'task_id': 'T002',
                'name': '运动鞋产品展示',
                'type': '🎬 视频混剪',
                'product': '运动跑步鞋',
                'progress': 75,
                'status': '🔄 进行中',
                'created': (now - timedelta(minutes=30)).strftime('%Y-%m-%d %H:%M'),
                'duration': '8分钟'
            },
            {
                'task_id': 'T003',
                'name': '手提包图片处理',
                'type': '🖼️ 图片处理',
                'product': '商务手提包',
                'progress': 0,
                'status': '⏳ 等待中',
                'created': (now - timedelta(minutes=10)).strftime('%Y-%m-%d %H:%M'),
                'duration': '-'
            },
            {
                'task_id': 'T004',
                'name': '面霜广告音频',
                'type': '🎵 音频处理',
                'product': '保湿面霜',
                'progress': 50,
                'status': '⏸️ 暂停',
                'created': (now - timedelta(hours=1)).strftime('%Y-%m-%d %H:%M'),
                'duration': '5分钟'
            },
            {
                'task_id': 'T005',
                'name': '耳机销售数据分析',
                'type': '📊 数据分析',
                'product': '无线蓝牙耳机',
                'progress': 0,
                'status': '❌ 失败',
                'created': (now - timedelta(hours=3)).strftime('%Y-%m-%d %H:%M'),
                'duration': '2分钟'
            }
        ]
        
        self.tasks = sample_tasks
        self.filtered_tasks = sample_tasks.copy()
        self.update_task_list()
    
    def update_task_list(self):
        """更新任务列表显示"""
        # 清空现有项目
        for item in self.task_tree.get_children():
            self.task_tree.delete(item)
        
        # 隐藏/显示空状态提示
        if self.filtered_tasks:
            self.empty_frame.pack_forget()
        else:
            self.empty_frame.place(relx=0.5, rely=0.5, anchor="center")
            return
        
        # 添加任务项目
        for task in self.filtered_tasks:
            # 根据状态设置标签
            status_tags = {
                '⏳ 等待中': 'waiting',
                '🔄 进行中': 'running',
                '✅ 已完成': 'completed',
                '❌ 失败': 'failed',
                '⏸️ 暂停': 'paused'
            }
            tag = status_tags.get(task['status'], '')
            
            # 进度显示
            progress_text = f"{task['progress']}%" if task['progress'] > 0 else "-"
            
            self.task_tree.insert('', 'end', values=(
                task['task_id'],
                task['name'],
                task['type'],
                task['product'],
                progress_text,
                task['status'],
                task['created'],
                task['duration']
            ), tags=(tag,))
        
        # 配置标签颜色
        self.task_tree.tag_configure('waiting', background=DesignSystem.COLORS['warning_bg'])
        self.task_tree.tag_configure('running', background=DesignSystem.COLORS['info_bg'])
        self.task_tree.tag_configure('completed', background=DesignSystem.COLORS['success_bg'])
        self.task_tree.tag_configure('failed', background=DesignSystem.COLORS['danger_bg'])
        self.task_tree.tag_configure('paused', background=DesignSystem.COLORS['gray_100'])
    
    def on_filter_changed(self, event=None):
        """筛选条件改变"""
        self.apply_filters()
    
    def on_search_changed(self, event=None):
        """搜索条件改变"""
        self.apply_filters()
    
    def apply_filters(self):
        """应用筛选条件"""
        status_filter = self.status_filter_var.get()
        type_filter = self.type_filter_var.get()
        search_text = self.search_var.get().lower()
        
        self.filtered_tasks = []
        
        for task in self.tasks:
            # 状态筛选
            if status_filter != "all" and task['status'] != status_filter:
                continue
            
            # 类型筛选
            if type_filter != "all" and task['type'] != type_filter:
                continue
            
            # 搜索筛选
            if search_text and (search_text not in task['name'].lower() and 
                               search_text not in task['task_id'].lower() and
                               search_text not in task['product'].lower()):
                continue
            
            self.filtered_tasks.append(task)
        
        self.update_task_list()
    
    def on_item_double_click(self, event):
        """双击项目事件"""
        selection = self.task_tree.selection()
        if selection:
            item = self.task_tree.item(selection[0])
            task_name = item['values'][1]
            messagebox.showinfo("任务详情", f"查看任务: {task_name}")
    
    def show_context_menu(self, event):
        """显示右键菜单"""
        item = self.task_tree.identify_row(event.y)
        if item:
            self.task_tree.selection_set(item)
            
            context_menu = tk.Menu(self.frame, tearoff=0)
            context_menu.add_command(label="查看详情", command=self.view_task_details)
            context_menu.add_command(label="查看日志", command=self.view_task_logs)
            context_menu.add_separator()
            context_menu.add_command(label="重新运行", command=self.restart_task)
            context_menu.add_command(label="暂停任务", command=self.pause_task)
            context_menu.add_command(label="停止任务", command=self.stop_task)
            context_menu.add_separator()
            context_menu.add_command(label="删除任务", command=self.delete_task)
            
            context_menu.tk_popup(event.x_root, event.y_root)
    
    def create_new_task(self):
        """创建新任务"""
        self.app.show_page("trigger_task")
    
    def batch_operations(self):
        """批量操作"""
        messagebox.showinfo("提示", "批量操作功能开发中...")
    
    def export_report(self):
        """导出报告"""
        messagebox.showinfo("提示", "导出报告功能开发中...")
    
    def clear_completed(self):
        """清理已完成任务"""
        if messagebox.askyesno("确认", "确定要清理所有已完成的任务吗？"):
            messagebox.showinfo("成功", "已完成任务清理完成")
    
    def view_task_details(self):
        """查看任务详情"""
        messagebox.showinfo("提示", "任务详情功能开发中...")
    
    def view_task_logs(self):
        """查看任务日志"""
        messagebox.showinfo("提示", "任务日志功能开发中...")
    
    def restart_task(self):
        """重新运行任务"""
        messagebox.showinfo("提示", "重新运行任务功能开发中...")
    
    def pause_task(self):
        """暂停任务"""
        messagebox.showinfo("提示", "暂停任务功能开发中...")
    
    def stop_task(self):
        """停止任务"""
        if messagebox.askyesno("确认", "确定要停止这个任务吗？"):
            messagebox.showinfo("成功", "任务已停止")
    
    def delete_task(self):
        """删除任务"""
        if messagebox.askyesno("确认删除", "确定要删除这个任务吗？\n\n此操作不可撤销！"):
            selection = self.task_tree.selection()
            if selection:
                self.task_tree.delete(selection[0])
                messagebox.showinfo("成功", "任务删除成功")
    
    def refresh_tasks(self):
        """刷新任务列表"""
        self.load_sample_data()
        messagebox.showinfo("成功", "任务列表已刷新")
